<?php
namespace app\admin\controller\v1;
use app\admin\Adminbase;
use think\Db;
use app\common\model\Order as OrderModel;

class Order extends Adminbase 
{
	
	/**
	* 发货
	* /admin/v1/Order/setOrderstatus
	* 需要登录 
	* @is_need_login true
	*/
	public function deliverGoods($id){
		$request =  request();
		$param = request() ->post();
		if(!$id){
			return $this->ReError('订单id不能为空！');
		}
		try {
			$model = model('order');
			$result = $model->send($param);
			if($result === false){
				return $this->ReError( $model->errorInfo );
			}
			return $this->ReSucess($result);	
		} catch (\Exception $e) {
			return $this->ReError($e->getMessage());	
		}
	}
	
    /**
	* 订单退款
	* /admin/v1/Order/refund
	* 需要登录 
	* @is_need_login true
	*/ 
    public function refund($id)
    {
     	if(!$id) return $this->ReError('订单id不能为空！');
		try {
			$model = model('order');
			$result = $model->refund($id);
			if($result === false){
				return $this->ReError( $model->errorInfo );
			}
			return $this->ReSucess($result);	
		} catch (\Exception $e) {
			return $this->ReError($e->getMessage());	
		}
    }

	 /**
	* 订单退款驳回
	* /admin/v1/Order/reject
	* 需要登录 
	* @is_need_login true
	*/ 
    public function reject($id,$desc='')
    {
    	if(!$id) return $this->ReError('订单id不能为空！');
    	if(empty($desc)) return $this->ReError('原因不能为空！');
		try {
			$model = model('order');
			$result = $model->rejectApply($id,$desc);
			if($result === false){
				return $this->ReError( $model->errorInfo );
			}
			return $this->ReSucess($result);	
		} catch (\Exception $e) {
			return $this->ReError($e->getMessage());	
		}
    }
	
	/**
	* 获取订单状态
	* /admin/v1/Order/getAllOrderstatuss
	* 需要登录 
	* @is_need_login true
	*/
	public function getAllOrderStatus(){
		$post_json = json_decode(file_get_contents("php://input"),true);
		
		try {
    		$result = model('Order')->alias("a")
				->where('a.is_del',0)
    			->fetchSql(false) 
    			->field('if(a.is_pay = 0 and a.status = 0,100,a.status) status') 
    			->select()->toArray();
			
			$status = array_column($result, 'status'); 
			$status = array_count_values($status);
			return $this->ReSucess($status);	
			
		} catch (\Exception $e) {
			return $this->ReError($e->getMessage());	
		}
	}
	
	/**
	* 获取订单交易信息
	* /admin/v1/Order/getAllOrderTradeInfo
	* 需要登录 
	* @is_need_login true
	*/
	public function getAllOrderTradeInfo(){
		try {
			$result = model('Order','Service')->getAllOrderTradeInfo();
			return $this->ReSucess(  $result );	
		} catch (\Exception $e) {
			return $this->ReError($e->getMessage());	
		}
	}
	
	/**
	* 获取订单交易信息-柱状图数据
	* /admin/v1/Order/getAllOrderTradeInfoDarData
	* 需要登录 
	* @is_need_login true
	*/
	public function getAllOrderTradeInfoDarData($mode=1){
		try {
			$result = model('Order','Service')->getAllOrderTradeInfoDarData($mode);
			return $this->ReSucess(  $result );	
		} catch (\Exception $e) {
			return $this->ReError($e->getMessage());	
		}
	}
	
	/**
	* 获取订单交易信息-饼图数据
	* /admin/v1/Order/getAllOrderTradeInfoBerData
	* 需要登录 
	* @is_need_login true
	*/
	public function getAllOrderTradeInfoBerData($mode=1){
		try {
			$result = model('Order','Service')->getAllOrderTradeInfoBerData($mode);
			return $this->ReSucess(  $result );	
		} catch (\Exception $e) {
			return $this->ReError($e->getMessage());	
		}
	}

    /**
     * 获取结算信息
     * /admin/v1/order/getSettlementInfo
     * 需要登录
     * @is_need_login true
     * @method post
     */
    public function getSettlementInfo($uid,$data,$coupon_id=0){
        try {
            //获取用户信息
            if( !$user = model('user')->getInfo($uid) ){
                return $this->ReError('用户id无效！');
            };
            //区分是否已购项目
            $goods = [];
            $ygProj = [];
            foreach(  json_decode($data,true) as $key => $item ){
            	if( $item['is_yg_proj']!=1 ){
            		$goods[] = $item;
            	}else{
            		$ygProj[] = $item;
            	}
            }
            
            //添加购物车 - 获取购物车id
            $cartIds = [];
            foreach( $goods as $key => $val ){
                $cart = model('ShopCart')->setCartInc($uid,$val['goods_id'],$val['id'],$val['num']??1,1);
                if($cart === false ){
                    return $this->ReError( model('ShopCart')->errorInfo );
                }
                $cartIds[] = $cart['id'];
            }
			
            // TODO 确认订单
            $res = model('order')->setBill(true)->setCoupon($coupon_id)->confirm($cartIds,$user);

            return $this->ReSucess($res);

        } catch (\Exception $e) {
            return $this->ReError($e->getMessage(),-2);
        }
    }
    
    /**
	* 确认
	* /admin/v1/order/confirm
	* 需要登录 
	* @is_need_login true
	* @method post
	*/
	public function confirm($orderKey,$uid,$data){
		if(!trim($orderKey) ) return $this->ReError('orderKe不能为空！');
        $userId = request()->userInfo['uid'] ?: request()->userInfo['user_id'];
        $shopId = request()->userInfo['shop_id'];
      	$identity = $shopId > 0 ? 2 : 1;
      	
		try {
			
			//区分是否已购项目
            $goods = [];
            $ygProj = [];
            $staffProfit = [];
            foreach(  json_decode($data,true) as $key => $item){
            	if( $item['is_yg_proj'] !=1 ){
            		$goods[] = $item;
            	}else{
            		$ygProj[] = $item;
            	}
            	if($item['staff_id']){
            		$staffProfit[] = ['specs_id'=>$item['id'],'staff_id'=>$item['staff_id'],'scale'=>$item['scale']];
            	}
            }

            //添加开单记录
            $bill = model('order_bill')->add($uid,$userId,$identity,$shopId,$staffProfit);
			
			//核销项目
            foreach( $ygProj as $key => $item){
        		model('UserYgProj')->where('id',$item['proj_id'])->setinc('use_num',$item['num']);
        		model('UserYgProjUseLog')->insert([
        			'link_id'=>$bill['bill_no'],
					'proj_id'=>$item['proj_id'],
					'use_num'=>$item['num'],
					'type'=>'2',
				]);
            }
        
			
			//生成订单
			if(count($goods) > 0){
				$dbOrder = model('Order');
		        $order = $dbOrder->setMark( request()->post('mark') )
		        	->setPayType('offline')
		        	->setBillId( $bill['id'] )
		        	->createOrder($orderKey);
		        
		       	$res = $order && $dbOrder->paySuccess( $order->order_no, 'offline');
		       	
		       	if($res){
		       		$order->is_pay = 1;
		       		$order = $dbOrder->tidyOrder($order);
		       	}
		       	
		       	event('OrderCreated', $order); 	//订单创建成功事件
			}
	       
			return $this->ReSucess();
			
		} catch (\Exception $e) {
			return $this->ReError( $e->getMessage() );
		}
	}


	/**
	* 获取订单礼品列表
	* /admin/v1/order/xmlGetGiftGrid
	* 需要登录 
	* @is_need_login true
	* @method post
	*/
	public function xmlGetGiftGrid(){
		try {
			$param= json_decode($this->request->param()['keyWord'],true);
			$orderId = $param['filter'][0]['value'];
			$info = OrderModel::where('id',$orderId)->value('info');
			$info =  json_decode($info,true);
			$data = [];
			foreach($info['reappeGroup']['gifts'] as $key => $gifts ){
				foreach($gifts['gift'] as $k => $gift ){
					$data[] = $gift;
				}
			}
			return [
				'total'=>count($data),
				'data'=>$data
			];
		} catch (\Exception $e) {
			return $this->ReError( $e->getMessage() );
		}
	}


    /**
     *获取订单明细
     * /admin/v1/order/details
     * 需要登录
     * @is_need_login true
     * @method all
     */
    public function details($id){
        if(!$id){
            return $this->ReError('订单id不能为空！');
        }
        try {
        	$result = model('order')->details($id);
            return $this->ReSucess($result);
        } catch (\Exception $e) {
        	 return $this->ReSucess();
            return $this->ReError( $e->getMessage() );
        }
    }

    /**
     *获取订单明细--商品购物车
     * /admin/v1/order/details_cart
     * 需要登录
     * @is_need_login true
     * @method all
     */
    public function details_cart(){
        //var_dump(request()->keyWord);die;    //input('pageIndex')
        $keyword=json_decode(request()->keyWord,true);
//        echo $keyword['filter'][0]['value'];die;
//        $id=request()->keyWord->filter;

        $id=$keyword['filter'][0]['value'];
        if(!$id){
            return $this->ReError('订单id不能为空！');
        }
        try {
            $result = model('admin/order')->details($id);
            $result->user_info = model('admin/user_vip')->where('uid',$result['uid'])->field('name,code')->find();

            $tables=json_decode($result,true);

            $res_data=[];
            foreach ($tables['info']['cartInfo'] as $k=>$v){
                $res_data[$k]['goods_name'] =$v['goods']['goods_name'];
                $res_data[$k]['stock'] =$v['goods']['stock'];
                $res_data[$k]['discounts'] =$v['goods']['discounts'];
                $res_data[$k]['sale_price'] =$v['goods']['sale_price'];
                $res_data[$k]['pay_num'] =$v['cart_num'];

            }

            $res_data['data']=$res_data;
            return $res_data;
        } catch (\Exception $e) {
            return $this->ReError( $e->getMessage() );
        }
    }

    /**
     * 客户详情下的累计消费（包含线下消费）
     * /admin/v1/order/get_all_pirce
     * 需要登录
     * @is_need_login true
     * @method all
     */
    public function get_all_pirce(){

        $keyword_array = json_decode($this->request->param('keyWord'),true);

        $uid='';
        foreach ($keyword_array['filter'] as $key => $value) {
            if($value['field']=='id'){
                $uid = $value['value'];
            }
        }

        if(!$uid){
            return $this->ReError('用户id不能为空！');
        }
        try {

            //用户账单的显示
            $res_data = model('admin/user_bill')
                ->field('a.uid as id,a.add_time,a.link_id,a.number,a.title ,ifnull(c.name,\'\') as shop_name ')
                ->alias('a')
                ->leftJoin("xw_order b","b.order_no = a.link_id")
                ->leftJoin("xw_shop c","c.id = b.shop_id")
                ->leftJoin("xw_user d","d.id = a.uid" )
                ->where("a.pm",0)
                ->where("a.category","in",['balance','wx','aplipay','offine'])
                ->where("a.shop_id=d.shop_id")
                ->where("a.uid",$uid)
                ->group('link_id')
                ->page(input('pageIndex') ?: 1,input('pageSize') ?: 20)
                ->order('a.add_time','desc')
                ->select();

            //线下消费
            $do_arry=array_merge(json_decode($res_data, true),$this->offine_data($uid));
            array_multisort( array_column($do_arry,'add_time'),SORT_DESC,$do_arry);

            //统计得到的总数
            $total_number=array_sum( array_column($do_arry,'number'));
            //file_put_contents('test.txt', date('Y-m-d H:i:s').'：'.json_encode($total_number, JSON_UNESCAPED_UNICODE)."\r\n\r\n", FILE_APPEND);
            $tables['sumNmber']= $total_number;
            $tables['data']= $do_arry;
            $tables['total']=count($do_arry);

            return $tables;
        } catch (\Exception $e) {
            return $this->ReError( $e->getMessage() );
        }
    }



    /**
     * 线下消费显示
     * /admin/v1/order/get_offine_pirce
     * 需要登录
     * @is_need_login true
     * @method all
     */
    public function get_offine_pirce(){

        $keyword_array = json_decode($this->request->param('keyWord'),true);

        $uid='';
        foreach ($keyword_array['filter'] as $key => $value) {
            if($value['field']=='id'){
                $uid = $value['value'];
            }
        }

        if(!$uid){
            return $this->ReError('用户id不能为空！');
        }

        try {
            $array_offine=$this->offine_data($uid);
            $tables['data']= $array_offine;
            $tables['total']=count($array_offine);
            return $tables;
        } catch (\Exception $e) {
            return $this->ReError( $e->getMessage() );
        }
    }

    //线上消费数据
    public  function offine_data($uid)
    {

            $res_data = model('admin/order')
                ->field('a.pay_price,a.add_time,b.name as shop_name,a.order_no,a.pay_type,a.info,a.shop_id')
                ->alias('a')
                ->leftJoin("(
               xw_shop b
            )", "b.id=a.shop_id")
                ->where('a.pay_type', 'offline')
                ->where('a.uid', $uid)
                ->where('a.shop_id', request()->userInfo['shop_id'])
                ->page(input('pageIndex') ?: 1, input('pageSize') ?: 20)
                ->order('a.add_time', 'desc')
                ->select();

            $array_res = json_decode($res_data, true);
            $tables = [];
            foreach ($array_res as $k => $v) {

                if (($v['pay_price'] - $v['info']['amountInfo']['deductPrice']) > 0) {

                    $tables[$k]['pay_price'] = $v['pay_price'];
                    $tables[$k]['add_time'] = $v['add_time'];
                    $tables[$k]['shop_name'] = $v['shop_name'];
                    $tables[$k]['link_id'] = $v['order_no'];
                    $tables[$k]['title'] = $v['pay_type'] == "offline" ? "线下付款" : "其他支付";
                    $tables[$k]['number'] = $v['pay_price'] - $v['info']['amountInfo']['deductPrice'];    //线下付款
                }

            }

            return $tables;

        }




	

}



